<?php
class Stock extends AppModel {
	var $name = 'Stock';
    var $validate = array(
        'code' => array(
            'isUnique' => array(
                'rule'       => 'isUnique',
                'allowEmpty' => false,
                'on'         => 'create',
                'message'    => 'This product code has already existed in database'
            )
        ),
        'stockist_id' => array(
            'numeric' => array(
                'rule'       => 'numeric',
                'allowEmpty' => false,
                'message'    => 'Stockist Id must be numeric number'
            )
        ),
        'product_id' => array(
            'numeric' => array(
                'rule'       => 'numeric',
                'allowEmpty' => false
            )
        ),
        'type' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
            )
        ),
        'in_out' => array(
            'numeric' => array(
                'rule'       => 'numeric',
                'allowEmpty' => false,
                'message'    => 'Quantity must be numeric number'
            )
        )
    );

    public function listing ($stockist_id) {
        $sql = 'SELECT p.`id`, p.`code`, p.`name`, p.`price` FROM `products` as p ' .
               'WHERE p.`status`!="D" ' .
               'ORDER BY p.`code` ASC';
        $data = $this->query($sql);

        if (count($data) > 0) {
            foreach ($data as $i=>$product) {
                $sql = 'SELECT SUM(`in_out`) AS `balance` FROM `stocks` WHERE `stockist_id`='.$stockist_id.' AND `product_id`='.$product['p']['id'];
                $bal = $this->query($sql);

                $data[$i]['s']['balance'] = empty($bal[0][0]['balance']) ? 0 : $bal[0][0]['balance'];
            }
            return $data;
        }

        return 0;
    } // listing
} // Stock
?>